package cn.edu.zjicm.wordsnet_d.activity;

import java.util.Stack;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.ViewFlipper;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.base.WordBaseActivity;
import cn.edu.zjicm.wordsnet_d.fragment.AddSchoolFragment;

public class AddSchoolActivity extends WordBaseActivity {

	public static void startActivity(Context context) {
		Intent in = new Intent(context, AddSchoolActivity.class);
		context.startActivity(in);
	}

	public SelectType type = SelectType.EDU;
	private FragmentTransaction ft;
	public int selectedID;
	public int schoolLevel;

	private ViewFlipper mFlipper;
	private TextView selectHint;
	private AddSchoolFragment addSchoolFragment;
	private Stack<AddSchoolFragment> fragmentStack;
	public boolean selectUniversity = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitleBarStyle(TITLE_BAR_STYLE_BACK_BUTTON);
		setTitleText("添加学校");
		setContentView(R.layout.activity_add_school);
		findView();
		initView();
	}

	private void initView() {
		fragmentStack = new Stack<AddSchoolFragment>();
		setBackButton(new OnClickListener() {
			@Override
			public void onClick(View v) {
				removeCurrentFragment();
			}
		});

		updateView();
	}

	private void findView() {
		mFlipper = (ViewFlipper) findViewById(R.id.add_school_flipper);
		selectHint = (TextView) findViewById(R.id.select_hint);
	}

	public void updateView() {
		selectHint.setText(type.hintStr);
		addSchoolFragment = new AddSchoolFragment(this, type, selectedID, schoolLevel);
		fragmentStack.push(addSchoolFragment);
		ft = getSupportFragmentManager().beginTransaction();
		ft.add(type.layoutId, addSchoolFragment);
		ft.commit();
		mFlipper.setDisplayedChild(type.index);
	}

	public static enum SelectType {
		EDU("选择学历", R.id.eduLayout, 0), PRO("选择省份", R.id.proLayout, 1), CITY("选择城市", R.id.cityLayout, 2), DIS("选择区", R.id.disLayout, 3), SCHOOL("选择所在学校", R.id.schoolLayout, 4);

		public String hintStr;
		public int layoutId;
		public int index;

		private SelectType(String hintStr, int layoutId, int index) {
			this.hintStr = hintStr;
			this.layoutId = layoutId;
			this.index = index;
		}
	}

	private void removeCurrentFragment() {
		if (fragmentStack.size() > 1) {
			ft = getSupportFragmentManager().beginTransaction();
			ft.remove(fragmentStack.pop());
			ft.commit();
			type = fragmentStack.peek().type;
			mFlipper.setDisplayedChild(type.index);
			selectHint.setText(type.hintStr);

		} else if (fragmentStack.size() == 1) {
			finish();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			removeCurrentFragment();
		}
		return true;
	}
}
